﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml.Linq;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using VietTrips.Domain.Contexts;
using VietTrips.Domain.Interfaces;
using VietTrips.Domain.Models;
using VietTrips.Domain.Repositories;
using VietTrips.Domain.Services;
using WebMatrix.WebData;
using VietTrips.WebUI.Filters;
using VietTrips.WebUI.Models;
using IsolationLevel = System.Transactions.IsolationLevel;

namespace VietTrips.WebUI.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        private readonly IUserRepository _userRepository;
        private readonly TourAgenciesService _tourAgenciesService;

        public AccountController(IUserRepository userRepository)
        {
            this._userRepository = userRepository;
            _tourAgenciesService = new TourAgenciesService();
        }
          
        // GET: /Account/Login
        // Chuyển đến trang Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        // Thực hiện việc Login và qua trở lại trang ban đầu
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToLocal(returnUrl);
            }
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "Tên Đăng Nhập hoặc Mật Khẩu không đúng.");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        // Đi đến trang Đăng Ký
        [AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.provinces = this.GetProvinces();
            return View();
        }

        //
        // POST: /Account/Register
        // Thự hiện thao tác Submit trong trang Đăng ký
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            ViewBag.provinces = this.GetProvinces();
            if (ModelState.IsValid)
            {
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, propertyValues: new
                    {
                        FullName = model.FullName,
                        Email = model.Email,
                        Phone = model.Phone,
                        Address = model.Address,
                        City = model.City,
                        DateOfBirth = model.DateOfBirth,
                        Female = model.Female,
                        CreatedDate = DateTime.UtcNow,
                        LastModified = DateTime.UtcNow
                    });

                    // Chỉ trùng trong bản Debug
                    #if DEBUG
                    Roles.AddUserToRole(model.UserName, model.Role);
                    #endif
                    // end

                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("UserName", ErrorCodeToString(e.StatusCode));
                }
                catch (SqlException)
                {
                    ModelState.AddModelError("Email", "Email này đã tồn tại trong hệ thống. Xin vui lòng đăng ký dưới email khác.");
                }
            }

            // Nếu ta đi đến đây nghĩa là đăng nhập không được, nên cần reload lại trang đăng ký
            return View(model);
        }

        //GET /Account/Agency
        //Đi đến trang Đăng Ký Công Ty
        public ActionResult RegisterAgency()
        {
            ViewBag.provinces = this.GetProvinces();
            return View();
        }

        //POST /Account/Agency
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RegisterAgency(RegisterAgencyModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var tourAgency = new TourAgency
                    {
                        TourAgencyName = model.TourAgencyName,
                        LogoImageUrl = model.LogoImageUrl,
                        Description = model.Description,
                        HotLine1 = model.HotLine1,
                        HotLine2 = model.HotLine2,
                        Fax = model.Fax,
                        Website = model.Website,
                        ManagerId = WebSecurity.CurrentUserId,
                        RequestStatus = TourAgency.StatusWaiting,
                        CreatedDate = DateTime.UtcNow,
                        LastModified = DateTime.UtcNow,
                    };
                    var address = new Address
                    {
                        TourAgency = tourAgency,
                        AddressContent = model.Address,
                        City = model.City,
                        PhoneLine1 = model.PhoneLine1
                    };

                    tourAgency.Addresses.Add(address);
                    _tourAgenciesService.RegisterNewAgency(tourAgency);
                    
                    return RedirectToAction("ManageAgency");
                }
            }
            catch(DataException)
            {
                ModelState.AddModelError("RegisterAgencyProblems", "Không thể lưu lại thay đổi. " +
                  "Xin hãy thử lại lần nữa, nếu vẫn không được xin hay liên hệ Admin hệ thống.");
            }
            return View();
        }

        public ActionResult ManageAgency()
        {
            var agency = _tourAgenciesService.GetAgencyByUser(User.Identity.Name);
            if (agency != null)
            {
                if (agency.RequestStatus == TourAgency.StatusAccepted)
                {
                    RedirectToAction("Dashboard", "Admin", new { Area = "Management" });
                }
                else
                {
                    Address address = null; 
                    if (agency.Addresses.Count > 0)
                    {
                        address = agency.Addresses.ElementAtOrDefault(0);
                    }

                    if (address != null)
                    {
                        var viewModel = new RegisterAgencyModel()
                        {
                            TourAgencyName = agency.TourAgencyName,
                            Address  = address.AddressContent,
                            City = address.City,
                            Country = address.Country,
                            PhoneLine1 = address.PhoneLine1,
                            Description = agency.Description,
                            Fax = agency.Fax,
                            HotLine1 = agency.HotLine1,
                            HotLine2 = agency.HotLine2,
                            LogoImageUrl = agency.LogoImageUrl
                        };
                        return View("NewAgencyWaiting", viewModel);
                    }
                }
            }
            return RedirectToAction("Index", "Home");
        }

        //
        // POST: /Account/Disassociate
        // Dùng cho việc đăng nhập bằng tài khoản FaceBook hoặc Google+
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.provinces = this.GetProvinces();
            int userId = WebSecurity.CurrentUserId;
            var userProfile = _userRepository.Find(userId);
            
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Mật khẩu đã được thay đổi."
                : message == ManageMessageId.SetPasswordSuccess ? "Mật khẩu đã được thiết lập."
                : message == ManageMessageId.RemoveLoginSuccess ? "Tài khoản dịch vụ đã bị xoá."
                : "";

            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            ViewBag.UserModel = userProfile;
            return View();
        }

        //
        // POST: /Account/Manage
        // Quản lý UserProfile đã đang được đăng nhập
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.provinces = this.GetProvinces();
            ViewBag.ReturnUrl = Url.Action("Manage");
            int userId = WebSecurity.CurrentUserId;
            var userProfile = _userRepository.Find(userId);

            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "Mật khẩu cũ không đúng hoặc Mật khẩu mới đặt sai quy định.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
                    }
                }
            }
            ViewBag.PasswordModel = model;
            ViewBag.UserModel = userProfile;
            // If we got this far, something failed, redisplay form
            //return View(model);
            return View();
        }

        public ActionResult ManageInformation(UserProfile model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.provinces = this.GetProvinces();
            ViewBag.ReturnUrl = Url.Action("Manage");

            // NotifyMessage và NotifyState d2ung để hiển thị Notification JS trên trang quản lý tài khoản
            ViewBag.NotifyMessage = @"Thay đổi thông tin cá nhân không thành công. "; 
            ViewBag.NotifyState = "danger";
            try
            {
                if (ModelState.IsValid)
                {
                    _userRepository.Update(model);
                    ViewBag.NotifyMessage = @"Thông tin của bạn đã được cập nhật. ";
                    ViewBag.NotifyState = "success";
                }
            }
            catch (Exception)
            {
                throw;
            }

            ViewBag.InfoTabActive = true; // InfoTabActive == true để khi về trang quản lý nó sẽ tự động chuyển sang tab Information
            ViewBag.UserModel = model; // Truyền Model UserProfile
            return View("Manage");
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new UsersContext())
                {
                    var user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Tên đăng nhập đã tồn tại. Vui lòng chọn tên khác.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        // Ajax check username có tồn tại hay chưa
        [HttpPost]
        public JsonResult DoesUserNameExist(string userName)
        {

            var user = Membership.GetUser(userName);

            return Json(user == null);
        }

        // Lấy list các tỉnh thành phố ở Việt Nam
        public IEnumerable<SelectListItem> GetProvinces()
        {
            const string relPath = "~/Content/Provinces.xml";
            var absPath = Server.MapPath(relPath);
            IEnumerable<SelectListItem> provinces = from proc in XDocument.Load(absPath).Descendants("Province")
                                                          select new SelectListItem
                                                          {
                                                              Text = (string)proc,
                                                              Value = (string)proc
                                                          };
            return provinces;
        } 

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Tên tài khoản đã tồn tại. Vui lòng sửa dụng tên tài khoản khác.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "Có sự cố trong quá trình \"Đăng Ký\". Vui lòng gọi Support hoặc liên hệ người quản trị để được giải quyết.";
            }
        }

        private static string ErrorCodeToKey(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "UserName";

                case MembershipCreateStatus.DuplicateEmail:
                    return "DuplicateEmail";

                case MembershipCreateStatus.InvalidPassword:
                    return "InvalidPassword";

                case MembershipCreateStatus.InvalidEmail:
                    return "InvalidEmail";

                case MembershipCreateStatus.InvalidAnswer:
                    return "InvalidAnswer";

                case MembershipCreateStatus.InvalidQuestion:
                    return "InvalidQuestion";

                case MembershipCreateStatus.InvalidUserName:
                    return "InvalidUserName";

                case MembershipCreateStatus.ProviderError:
                    return "ProviderError";

                case MembershipCreateStatus.UserRejected:
                    return "UserRejected";

                default:
                    return "DefaultProblems";
            }
        }
        #endregion
    }
}
